<template>
    <div>
        <!--  三级分类全局组件 -->
        <Category :showAttr="showAttr" />
    </div>
    <el-card style="margin:10px 0">
        <div v-if="showAttr">
            <el-button type="primary" size="default" icon="Plus" :disabled="categoryStore.c3Id ? false : true"
                @click="addEvent">添加属性</el-button>
            <el-table border style="margin:10px 0" :data="AttrArr">
                <el-table-column label="序号" type="index" align="center" width="100px"></el-table-column>
                <el-table-column label="属性名称" align="center" width="200px" prop="attrName"></el-table-column>
                <el-table-column label="属性值名称" align="center">
                    <template #="{ row, $index }">
                        <el-tag v-for="item in row.attrValueList" style="margin: 0 5px" :key="item.id">{{ item.valueName
                        }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200px" align="center">
                    <template #="{ row, $index }">
                        <el-button type="primary" size="small" icon="Edit" @click="updateAttr(row)"></el-button>
                        <el-popconfirm :title="`确认删除${row.attrName}🐎?`" @confirm=" deleteAttr(row.id)">
                            <template #reference>
                                <el-button type=" primary" size="small" icon="Delete"></el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="!showAttr">
            <el-form :inline="true">
                <el-form-item label="属性名称:">
                    <el-input placeholder="请输入属性名称" width="80px" v-model="addAttr.attrName"></el-input>
                </el-form-item>
            </el-form>
            <el-button type="primary" size="default" icon="Plus" @click="addAttrValue"
                :disabled="addAttr.attrName ? false : true">添加属性值</el-button>
            <el-button type="primary" size="default">取消</el-button>
            <el-table border style="margin: 20px 0" :data="addAttr.attrValueList">
                <el-table-column width="120px" label="序号" type="index" align="center"></el-table-column>
                <el-table-column label="属性值的名称">
                    <!-- row为当前的属性值对象 -->
                    <template #="{ row, $index }">
                        <el-input :ref="(vc: any) => inputArr[$index] = vc" placeholder="请输入属性值名称"
                            @blur="toLook(row, $index)" v-if="row.flag" v-model="row.valueName"></el-input>
                        <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="属性值的操作"></el-table-column>
            </el-table>
            <el-button type="primary" icon="Plus" size="default" @click="save"
                :disabled="addAttr.attrValueList.length > 0 ? false : true">保存</el-button>
            <el-button type="primary" icon="Plus" size="default" @click="showAttr = !showAttr">取消</el-button>
        </div>
    </el-card>
</template>
<script setup lang='ts'>
//引入分类数据的仓库
import useCateGoryStore from '@/store/modules/category';
//实例化仓库
let categoryStore = useCateGoryStore()
import { ref, reactive, watch, nextTick, onBeforeUnmount } from 'vue'
//导入获取属性数据的函数
import { reqAddOrUpdateAttr, reqAttr, reqDeleteAttr } from '@/api/product/attr';
//导入数据类型
import type { resAttr, attrDate, attrValue } from '@/api/product/attr/type'
import { ElMessage } from 'element-plus';
//定义控制显隐属性的属性值
let showAttr = ref<boolean>(true)
//定义属性数据数组
let AttrArr = ref<attrDate[]>([])

//定义一个数组用来存储input组件实例
let inputArr = ref<any>([])

//定义新增属性对象
let addAttr = reactive<attrDate>({
    attrName: "",//新增的属性的名字
    attrValueList: [//新增的属性值数组
    ],
    categoryId: '',//三级分类的ID4
    categoryLevel: 3
})
//定义修改属性的方法

const updateAttr = (row: attrDate) => {
    showAttr.value = !showAttr.value
    //ES6合并语句
    Object.assign(addAttr, JSON.parse(JSON.stringify(row)))
}
//添加属性按钮的回调
const addEvent = () => {
    Object.assign(addAttr, {
        attrName: "",//新增的属性的名字
        attrValueList: [//新增的属性值数组
        ],
        categoryId: '',//三级分类的ID4
        categoryLevel: 3
    })

    //切换显示状态
    showAttr.value = !showAttr.value
}


//保存按钮的回调
const save = async () => {
    //收集参数
    addAttr.categoryId = categoryStore.c3Id;
    //发起请求
    let result: any = await reqAddOrUpdateAttr(addAttr);
    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: addAttr.id ? '修改成功' : '添加成功'
        })
        getAttr();
    } else {
        ElMessage({
            type: "error",
            message: addAttr.id ? '修改失败' : '添加失败'
        })
    }
    showAttr.value = true;
}

//定义一个添加属性值的方法
const addAttrValue = () => {
    //点击按钮时给新增对象添加一个属性值对象
    addAttr.attrValueList.push({
        valueName: '',
        flag: true,//控制属性值在编辑模式和查看模式之间切换
    })
    nextTick(() => {
        inputArr.value[addAttr.attrValueList.length - 1].focus();
    })
}
//观测c3Id从而控制显隐
watch(() => categoryStore.c3Id, () => {
    if (categoryStore.c3Id) {
        getAttr()
    } else { return; }
})

//定义获取数据的函数
const getAttr = async () => {
    const { c1Id, c2Id, c3Id } = categoryStore;
    let result: resAttr = await reqAttr(c1Id, c2Id, c3Id)
    AttrArr.value = result.data;
}
//定义失去焦点的方法
const toLook = (row: attrValue, $index: number) => {
    if (row.valueName.trim() == '') {
        addAttr.attrValueList.splice($index, 1)
        ElMessage({
            type: 'error',
            message: '属性值不能为空!'
        })
        return;
    }
    let repeat = addAttr.attrValueList.find((item) => {
        //切记把当前输入的数据排除判断
        if (item != row) {
            return item.valueName === row.valueName;
        }
    })
    if (repeat) {
        //去重数据
        addAttr.attrValueList.splice($index, 1);
        ElMessage({
            type: 'error',
            message: '属性值不能重复!'
        })
        return;
    }
    row.flag = true;
}
//定义点击div的方法
const toEdit = (row: attrValue, $index: number) => {
    row.flag = false;
    //nextTick 当响应式数据发生变化,获取更新的dom元素.
    nextTick(() => {
        inputArr.value[$index].focus();
    })
}

//删除已有属性的方法
const deleteAttr = async (id: string | number) => {
    let result: any = await reqDeleteAttr(id)
    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: '删除成功'
        })
        getAttr();
    } else {
        ElMessage({
            type: 'error',
            message: '删除失败'
        })
    }
}

//组件卸载时触发
onBeforeUnmount(() => {
    //清空仓库的数据
    categoryStore.$reset()
})
</script>
<style lang='scss' scoped></style>